// pages/launchTopic/launchTopic.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pathImg: ' ',
    temPath: [],
    numbers: 0,
    thumb_id: '',
    disabled: false,
    description: '',
    title: []
  },

  //拿到描述内容
  onTopicDescription: function (e) {
    var description = e.detail.value;
    var that = this;
    that.setData({
      description: description
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var discussId = options.discussId;
    var that = this;
    wx.setNavigationBarTitle({
      title: options.title,
    })
    
    
    that.setData({
      discussId: discussId,
      temPath: [],
      numbers: 0
    })
  },
  
  //把utf16的emoji表情字符进行转码成八进制的字符

  utf16toEntities: function (str) {

    var patt = /[\ud800-\udbff][\udc00-\udfff]/g; // 检测utf16字符正则  

    return str.replace(patt, function (char) {

      var H, L, code;

      if (char.length === 2) {

        H = char.charCodeAt(0); // 取出高位  

        L = char.charCodeAt(1); // 取出低位  

        code = (H - 0xD800) * 0x400 + 0x10000 + L - 0xDC00; // 转换算法  

        return "&#" + code + ";";

      } else {

        return char;

      }

    });

  },

  //发帖zi
  onLaunchTopic: function(){
    var that = this;
    if(that.data.description == ' '){
      wx.showToast({
        title: '请填写描述内容',
        icon: 'none'
      })
    }else{
      var time = 2;
      that.setData({
        disabled: true
      })
      var Interval = setInterval(function () {
        time--;
        if (time > 0) {
          that.setData({
            disabled: true
          })
        } else {
          clearInterval(Interval);
          that.setData({
            disabled: false
          })
        }
      }, 1000)
      that.onDetectionWord();
    }
  },

  //开始检测
  onDetectionWord: function () {
    var that = this;
    var str = that.data.description;
    that.isfindViolationStr(str);
  },

  //自定义匹配字段检测接口
  biddenStr: function (str) {
    var that = this;
    var forbiddenArray = ['代课', '代寝', '代课', 'daikao', 'daike', 'daiqin'];
    var re = '';
    for (var i = 0; i < forbiddenArray.length; i++) {
      if (i == forbiddenArray.length - 1)
        re += forbiddenArray[i];
      else
        re += forbiddenArray[i] + "|";
    }
    var pattern = new RegExp(re, "g");
    var judge = 0;
    if (pattern.test(str)) {
      judge = 1;
    }
    if (judge == 0) {
      wx.showLoading({
        title: '发帖审核中',
      })
      var tempath = wx.getStorageSync("tempath");
      var user_id = wx.getStorageSync('user_id');
      if (tempath.length == 0) {
        that.onLaunchTopicNoPages(user_id);
      } else {
        that.onLaunchTopicPages(user_id);
      }
    } else {
      wx.showToast({
        title: '存在敏感词',
        icon: 'none',
        duration: 2000,
        success: res => {
          that.setData({
            bflage: false
          })
        }
      })
    }
  },

  //官方检测接口
  isfindViolationStr: function (str) {
    var that = this;
    wx.request({
      url: 'https://api.geek51.cn/wx/word/',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        'content': str
      },
      success: res => {
        if (res.data.error == 500) {
          wx.showToast({
            title: '存在敏感词',
            icon: 'none',
            duration: 1000,
            success: res => {
              that.setData({
                bflage: false
              })
            }
          })
        } else {
          that.biddenStr(str);
        }
      }
    })
  },

  //发帖
  onLaunchTopicNoPages: function(user_id){
    var that = this;
    var description=that.utf16toEntities(that.data.description)
    wx.request({
      url: app.globalData.targetUrl + 'discuss/topics/',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        'user_id': user_id,
        'discuss_id': that.data.discussId,
        'type_id': '1',
        'description': description,
        'content': '发第一条帖',
      },
      success: res => {
        wx.hideLoading;
        var topic_id = res.data.data.topic_id;
        wx.showToast({
          title: '上传完成',
          success: function (res) {
            //增加发帖记录
            that.onAddLaunchRecord(user_id, topic_id);
            wx.navigateBack({
              delta: 1
            })
            /*wx.redirectTo({
              url: '/pages/lifeCircle/postList?discuss_id=' + that.data.discussId,
            })*/
          }
        })
      }
    })
  },

  //发帖(带图片)
  onLaunchTopicPages: function (user_id){
    var that = this;
    var imgId = [];
    
    var tempath = wx.getStorageSync("tempath");
    var numbers = tempath.length;
    that.setData({
      temPath: tempath,
      numbers: numbers,
    })
    var i = 0;
    var mid = "";
    var path = that.data.temPath;
    that.upimg(i, mid, imgId, user_id);
  },

  upimg: function (i, mid, imgId, user_id) {
    var that = this;
    //var description=that.utf16toEntities(that.data.description)
    var path = that.data.temPath;
    wx.uploadFile({
      url: app.globalData.targetUrl + 'upload/image/',
      filePath: that.data.temPath[i],
      name: 'img',
      header: {
        'Content-type': 'application/x-www-form-urlencoded'
      },
      formData: {
        'user_id': user_id
      },
      success: function (res) {
        var data = JSON.parse(res.data).data;
        var thumb_url = data.thumb_url;
        
        imgId.push(data.image_id);
        mid = mid + data.image_id + ";";
        that.setData({
          pathImg: mid,
          thumb_url: thumb_url
        })
      },
      complete: () => {
        i++;
        if (i == path.length) {
          var p1 = that.data.inputPrice;
          var p2 = parseFloat(p1).toFixed(2);
          that.setData({
            thumb_id: imgId[0],
            inputPrice: p2
          })
          var description = that.utf16toEntities(that.data.description);
          wx.request({
            url: app.globalData.targetUrl + 'discuss/topics/',
            method: 'POST',
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            data: {
              'user_id': user_id,
              'discuss_id': that.data.discussId,
              'type_id': '1',
              'description': description,
              'image_id': that.data.thumb_id,
              //'image_url': that.data.thumb_url
            }, //给服务器传递数据
            success: function (res) {
              wx.hideLoading;
              var topic_id = res.data.data.topic_id;
              if (res.data.error == 500) {
                wx.showToast({
                  title: '图片上传出现问题',
                  icon: 'none'
                })
              } else {
                wx.removeStorageSync("tempath");
                that.setData({
                  numbers: 0,
                  temPath: [],
                  index: 0,
                });
                wx.showToast({
                  title: '上传完成',
                  success: function(res){
                    //增加发帖记录
                    that.onAddLaunchRecord(user_id, topic_id);
                    wx.navigateBack({
                      delta: 1
                    })
                    /*wx.redirectTo({
                      url: '/pages/lifeCircle/postList?discuss_id=' + that.data.discussId,
                    })*/
                  }
                })
              }
            }
          });

        } else {
          that.upimg(i, mid, imgId, user_id);    //user_id
        }
      }
    })
  },

  //增加发帖记录
  onAddLaunchRecord: function(user_id, topic_id){
    var that= this;
    wx.request({
      url: app.globalData.targetUrl + 'history/topic/',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        user_id: user_id,
        is_publish: 1,
        topic_id: topic_id
      }
    })
  },
  onShow:function(){
    app.globalData.isReturn=true;
  }

})